<template>
    <van-nav-bar left-arrow @click-left="onClickLeft">
        <template #right>
            <!-- 输入框组件 -->
            <!-- 可以使用 CellGroup 作为容器 -->
            <van-cell-group inset>
                <van-field v-model="input" placeholder="搜索" />
            </van-cell-group>
            <van-icon name="search" size="22" @click="getSearchFn" />
        </template>
    </van-nav-bar>

    <div class="history-box">
        <div v-if="_history.arr.length != 0">
            <p style="display: flex; justify-content: space-between;">
                <span>历史搜索</span> 
                <span @click="emptyHistoryFn">清空</span>
            </p>
            <ul>
                <li v-for="item in _history.arr" :key="item" @click="addClick(item.name)">
                   <span> {{ item.name }}</span>
                   <button class="del" @click.capture="removeHistoryFn(item.id)">×</button>
                </li>
            </ul>
        </div>
    </div>

    <div class="list-box">
        <div v-if="search.list.length != 0">
            <p>搜索结果</p>
            <ul>
                <li v-for="item in search.list" :key="item.id">
                    <router-link :to="{
                        path: '/detail',
                        query: {
                            article_id: item.article_id,
                            article_type: item.article_type
                        }
                    }">
                        {{ item.article_title }}
                    </router-link>
                </li>
            </ul>
        </div>
        <div v-else>
            <van-empty description="没有搜索内容" />
        </div>
    </div>

    <div style="text-align: center;">
        <van-loading type="spinner" size="24" v-if="isLoading" />
    </div>
</template>
<script setup lang="ts">
import { ref, reactive } from 'vue'
import { getSearchArticleList } from '../api/index'
import { useRouter } from 'vue-router'
const $router = useRouter()
let input = ref('')
let isLoading = ref(false)
let search: any = reactive({ list: [] })
let _history: any = reactive({ arr: [] })


const onClickLeft = () => {
    $router.back();
}
let arr: any = [];
let str = localStorage.getItem('_HISTORY');
// console.log(str)
if (str) {
    arr = JSON.parse(str)
    _history.arr = arr;
}

// 编写搜索文章的方法
const getSearchFn = async () => {
    // 判断输入框是否为空
    if (input.value == "") return
    // 显示加载提示
    isLoading.value = true
    // 判断关键字是否存在 (至少一个条件成立，返回结果true)
    let isHas = arr.some((item: { id: string, name: string }) => item.name == input.value)
    console.log(isHas)
    // 不存在 就添加缓存
    if (!isHas) {
        arr.push({
            id: Math.random().toString().slice(2),
            name: input.value
        })
        localStorage.setItem('_HISTORY', JSON.stringify(arr))
        _history.arr = arr
    }
    else {
        _history.arr = arr
    }
    await getSearchArticleList({ keyword: input.value })
        .then(
            content => {
                console.log('1.0', content)
                if (content.code == 200) {
                    search.list = content.result;
                    // 重置输入框
                    input.value = ""
                }
            }
        )
    //隐藏加载提示
    isLoading.value = false
}

// 编写点击历史关键字的方法
const addClick = (name: string) => {
    // 获取历史关键字
    input.value = name;
    // 调用搜索方法
    getSearchFn();
}

// 编写点击清空历史关键字
const emptyHistoryFn = ()=> {
    localStorage.removeItem('_HISTORY')
    arr = []
    _history.arr = []
}

// 编写点击删除关键字的方法
const removeHistoryFn = (id:string)=> {
    if(Array.isArray(arr)){
        let res = arr.filter(item=>{
            return item.id != id;
        })
        arr = res
        _history.arr = res
        localStorage.setItem('_HISTORY', JSON.stringify(res))
    }
}


</script>

<style lang="less">
:root {
    --van-nav-bar-icon-color: #000;
}

.history-box {
    padding: 0 .4rem;

    p {
        height: 32px;
        line-height: 32px;
    }

    ul {
        &::after {
            content: "";
            display: block;
            clear: both;
        }

        li {
            float: left;
            padding: .1333rem .2667rem;
            margin: .2667rem .2667rem;
            border: 1px solid #ccc;
            border-radius: .1333rem;
            color: #666;
            font-size: 14px;
            position: relative;
            span {
                color: #555;
            }
            .del {
                background-color: transparent;
                border: 0;
                position: absolute;
                right:-10px;
                top: -12px;
                font-size: 20px;
                color: #ccc;
                width: 20px;
                height: 20px;
                border-radius: 50%;
            }
        }
    }
}

.list-box {
    padding: 0 .4rem;

    p {
        height: 32px;
        line-height: 32px;
    }

    ul {
        li {
            a {
                display: block;
                width: 100%;
                padding: .2667rem 0;
                border-block-end: 1px dashed #ccc;
                color: #666;
            }
        }
    }
}
</style>